package com.bcxk.order.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.bcxk.common.JwtUtil;
import com.bcxk.constants.Constants;
import com.bcxk.entity.dto.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author NieMingkun
 * 登录拦截器 获取token 验证是否正确 否则 返回登录页面
 */
public class LoginInterceptor  extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("token");
        if (null == token){
            response.sendRedirect("http://localhost:8989/login");
        }
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = JwtUtil.verify(token);
        } catch (Exception e) {
            response.sendRedirect("http://localhost:8989/login");
        }
        String userJson = decodedJWT.getClaim("USER_INFO").asString();
        User user = Constants.OBJECT_MAPPER.readValue(userJson, User.class);
        request.setAttribute("USER_INFO", user);
        return super.preHandle(request, response, handler);    }
}
